package com.lynch.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.os.Environment;

import com.lynch.model.Mp3Info;

public class FileUtils {
	private String SDCardRoot;

	public FileUtils() {
		//�õ���ǰ�ⲿ�洢�豸��Ŀ¼
		// /SDCARD
		SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
	}
	/**
	 * ��SD���ϴ����ļ�
	 * 
	 * @throws IOException
	 */
	public File creatFileInSDCard(String fileName, String dir) throws IOException {
		
		System.out.println("�ļ����󴴽�");
		System.out.println("�ļ�·��="+SDCardRoot + dir + File.separator + fileName);
		File file = new File(SDCardRoot + dir + File.separator + fileName);
		System.out.println("�ļ����󴴽��ɹ�");
		boolean aa = file.createNewFile();
		System.out.println("�ļ������ɹ�=" +aa);
		return file;
	}
	
	/**
	 * ��SD���ϴ���Ŀ¼
	 * 
	 * @param dirName
	 */
	public File creatSDDir(String dir) {
		File dirFile = new File(SDCardRoot + dir + File.separator);
		System.out.println("����Ŀ¼�ɹ�û==="+ dirFile.mkdirs());
		return dirFile;
	}

	/**
	 * �ж�SD���ϵ��ļ����Ƿ����
	 */
	public boolean isFileExist(String fileName, String path){
		File file = new File(SDCardRoot + path + File.separator +fileName);
		return file.exists();
	}
	
	/**
	 * ��һ��InputStream��������д�뵽SD����
	 */
	public File write2SDFromInput(String path,String fileName,InputStream input){
		
		File file = null;
		OutputStream output = null;
		try{
			creatSDDir(path);
			System.out.println("�����ļ���ǰ");
			file = creatFileInSDCard(fileName, path);
			System.out.println("�����ļ��Ժ�");
			System.out.println("file----->"+file);
			output = new FileOutputStream(file);
			byte buffer [] = new byte[4 * 1024];
			int temp;
			while((temp = input.read(buffer)) != -1){
				output.write(buffer,0,temp);
			}
			output.flush();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			try{
				output.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		return file;
	}
	
	
	/**
	 * 读取目录中的mp3文件的名字和大小 
	 */
	public List<Mp3Info> getMp3Files(String path){
		
		List<Mp3Info> mp3List= new ArrayList<Mp3Info>();
		File file = new File(SDCardRoot+File.separator+path);
		File[] files = file.listFiles();
		if(files!=null){
			for(int i=0;i<files.length;i++){
				if(!files[i].getName().endsWith("lrc")){
					Mp3Info mp3Info = new Mp3Info();
					mp3Info.setMp3Name(files[i].getName());
					mp3Info.setMp3Size(files[i].length()+"");
					mp3Info.setLrcName(mp3Info.getMp3Name().replace(".mp3", ".lrc"));
					mp3List.add(mp3Info);
				}
			}
		}
		
		return mp3List;
	}
	
	

}